package com.core.system.utils;

import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class ConvertUtils {


    // 类型转换方法 将 List<?> 转换 为 List<T>
    public static <T> List<T> Convert(List<?> source, T target){
        return source.stream().map(l -> {
            try {
                Object o = target.getClass().getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(l, o);
                return  (T)o;
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
    }

    // 类型转换方法 将 List<?> 转换 为 List<T>
    public static <T> List<T> Convert(List<?> source, Class<T> target){
        return source.stream().map(l -> {
            try {
                Object o = target.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(l, o);
                return  (T)o;
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
    }

    @SneakyThrows
    public static <T> T Convert(Object source, Class<T> clazz)  {
        Object o = clazz.getDeclaredConstructor().newInstance();
        BeanUtils.copyProperties(source,o);
        return (T)o;
    }


}
